package com.multiple.sources.core.config.aspect;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.multiple.sources.core.config.DbContextHolder;


@Aspect
@Order(-1) // 保证该执行顺序
@Component
public class MultipleSourcesAspect {
	
	@Pointcut("execution(public * com.multiple.sources.core.servie..*.*(..))")
	public void webLog() {
	}
	@Before("webLog()")
	public void changeDataSource(JoinPoint point) throws Throwable {

		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		getContextHolderInfo(request);
	}
	
	private void getContextHolderInfo(HttpServletRequest request) {
		// TODO Auto-generated method stub
		String userId = request.getParameter("userId");
		String dataSource = "";

		/*if (StringUtils.isEmpty(userId)) {
			dataSource = "dataSource";
		} else {
			if (userId.equals("1")) {
				dataSource = "test1";
			} else if (userId.equals("2")) {
				dataSource = "test2";
			}else if(userId.equals("3")){
				dataSource = "test3";
			}
			
		}*/
		DbContextHolder.setDBType(userId);
	}
	@AfterReturning(returning = "ret", pointcut = "webLog()")
	public void restoreDataSource(JoinPoint point) {

		//DbContextHolder.clearDBType();

	}
}
